import axios from 'axios'
import iView from 'iview'
import store from '@/store'
import { Modal } from 'iview'
import { getToken } from '@/libs/util'

/**
 *
 * @param {*} errorInfo
 */
const addErrorLog = errorInfo => {
    const { statusText, status, request: { responseURL } } = errorInfo
    let info = {
        type: 'ajax',
        code: status,
        mes: statusText,
        url: responseURL
    }
    if (!responseURL.includes('save_error_logger')) {
        store.dispatch('addErrorLog', info)
    }
}

class HttpRequest {
    constructor(baseUrl = baseURL, defaultPrefix = defaultPrefix) {
        this.baseUrl = baseUrl
        this.defaultPrefix = defaultPrefix
        this.queue = {}
    }

    /**
     *
     */
    getInsideConfig() {
        let device = 'web';
        let version = '1.0.0';
        let timestamp = new Date().getTime();

        const config = {
            timeout: 10000,
            baseURL: this.baseUrl,
            headers: {
                "Authorization-Device": device,
                "Authorization-Version": version,
                "Authorization-Timestamp": timestamp,
                "Authorization": "Bearer " + getToken(),
                "Content-Type": "application/json;charset=utf-8"
            }
        }
        return config
    }

    /**
     *
     * @param {*} url
     */
    destroy(url) {
        debugger
        delete this.queue[url]
        if (!Object.keys(this.queue).length) {
            // Spin.hide()
        }
    }

    /**
     *
     * @param {*} error
     * @param {*} errorInfo
     */
    showError(error, errorInfo) {
        debugger
        let message = "接口服务错误,请稍候再试.";

        let statusCode = -1;
        if (error.response && error.response.status) {
            statusCode = error.response.status;
        }
        switch (statusCode) {
            case 401:
                message = "接口服务错误,原因:未授权的访问(没有权限或者登录已超时)";
                break;
            case 500:
                message = "接口服务错误,原因:[" + error.response.statusText + "]";
                break;
            case -1:
                message = "网络出错,请检查你的网络或者服务是否可用<br />请求地址:[" + error.config.url + "]";
                break;
        }
        Modal.error({
            title: "错误提示",
            content: message,
            duration: 15,
            closable: false
        });
        iView.LoadingBar.finish();
    }

    /**
     *
     * @param {*} instance
     * @param {*} url
     */
    interceptors(instance, url) {
        /**
         * axios的访问前钩子，在每次访问前会都会进行的操作
         * 这里包括两个回调函数，第一个为请求正常的回调，第二个为异常的回调，这里的异常回调也包括在成功回调时发生错误的情况
         */
        instance.interceptors.request.use(config => {
            debugger
            // 添加全局的loading...
            if (!Object.keys(this.queue).length) {
                iView.LoadingBar.start();
            }
            this.queue[url] = true
            return config
        }, error => {
            return Promise.reject(error)
        })

        /**
         * axios响应后的钩子，每次响应接受后、分发前，都会调用这个钩子
         */
        instance.interceptors.response.use(res => {
            debugger
            iView.LoadingBar.finish();
            this.destroy(url)
            const { data, status } = res
            return { data, status }
        }, error => {
            debugger
            this.destroy(url)
            let errorInfo = error.response
            if (!errorInfo) {
                const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
                errorInfo = {
                    statusText,
                    status,
                    request: { responseURL: config.url }
                }
            }
            addErrorLog(errorInfo)
            if (error.config.hideError == null || error.config.hideError == false) {
                this.showError(error);
            }
            iView.LoadingBar.finish();
            return Promise.reject(error)
        })
    }

    /**
     *
     * @param {*} options
     */
    request(options) {
        debugger
        const instance = axios.create()
        let withPrefix = true
        if (options.withPrefix !== undefined && options.withPrefix == false) {
            withPrefix = false
        }
        let url = options.url
        if (options.prefix !== undefined && options.prefix.length > 0) {
            url = options.prefix + options.url
        } else if (withPrefix) {
            url = this.defaultPrefix + options.url
        }
        options.url = url
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}
export default HttpRequest